package com.cqjtu.eecs.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.cqjtu.eecs.entity.Course;
import com.cqjtu.eecs.entity.CourseSystem;
import com.cqjtu.eecs.entity.vo.CourseVO;
import com.cqjtu.eecs.entity.vo.CourseVO2;
import com.cqjtu.eecs.mapper.CourseMapper;
import com.cqjtu.eecs.service.ICourseService;
import com.cqjtu.eecs.service.ICourseSystemService;
import com.cqjtu.eecs.utils.ExcelUtils;
import com.cqjtu.eecs.utils.MapUtils;
import com.cqjtu.eecs.utils.Result;
import com.cqjtu.eecs.utils.ResultCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.DataSource;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.*;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author  重交岳云鹏
 * @since 2022-02-28
 */
@RestController
@RequestMapping("/course")
@Api(tags = "课程管理")
@Slf4j
public class CourseController {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ICourseService iCourseService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ICourseSystemService iCourseSystemService;
    @Autowired
    private MapUtils mapUtils;

    @ApiOperation("增加新的课程,课程代码可以忽略后台已经处理过了")
    @PostMapping("/insert")
    public  String insert(@RequestBody Course course) throws JsonProcessingException {
        boolean save = iCourseService.save(course);
        if (save) {
            return objectMapper.writeValueAsString(Result.success());
        }
        return objectMapper.writeValueAsString(Result.error());
    }

    @ApiOperation("根据课程id删除课程")
    @DeleteMapping("/deleteCourseById/{id}")
    public  String delete(@PathVariable("id") Integer id) throws JsonProcessingException {
        int flag= iCourseService.deletCourseById(id);
        if (flag==1) {
            return objectMapper.writeValueAsString(Result.success());
        }
        return objectMapper.writeValueAsString(Result.error(-1, "该课程可能已经删除，不存在！"));
    }

    @ApiOperation("根据课程id修改课程")
    @PutMapping("/putCourse")
    public  String putCourse(@RequestBody Course course) throws JsonProcessingException {
        int i = iCourseService.updateCourseByCourseCode(course.getCourseId(), course);
        if (i == 1) {
            return objectMapper.writeValueAsString(Result.success());
        }
        return objectMapper.writeValueAsString(Result.error());
    }

    @ApiOperation("查询所有课程-分页查询")
    @GetMapping("/selectAllCourse/{currPage}/{pageSize}")
    public  Result selectAllCourse(@PathVariable("currPage") Integer currPage, @PathVariable("pageSize") Integer pageSize) {
        int currPage_old=currPage;
        currPage=(currPage-1)*pageSize;
        List<Course> courses = iCourseService.selectAllCourselimit(currPage,pageSize);
        List<CourseVO> result=new ArrayList<>();
        Map<Integer, String> mapUtilsCourseSystemUtil = mapUtils.getCourseSystemUtil();
        for (int i=0;i<courses.size();i++){
            Course temp=courses.get(i);
            result.add(new CourseVO(temp.getCourseId(),temp.getCourseSystemId(),mapUtilsCourseSystemUtil.get(temp.getCourseSystemId()),temp.getCourseName(),temp.getReferenceCredit()));
        }
        return Result.success(new CourseVO2(
                iCourseService.count(),
                currPage_old,
                pageSize,
                result
        ));
    }


    @ApiOperation("通过excel批量导入课程")
    @PostMapping("/importCoursesByExcel")
    @Transactional
    public  Result importCoursesByExcel(MultipartFile file) throws Exception {
        if(file==null){
            return Result.error(-1,"请上传文件！！");
        }
        InputStream inputStream = file.getInputStream();
        List<List<Object>> data = ExcelUtils.getCourseListByExcel(inputStream, file.getOriginalFilename());
        ArrayList<CourseSystem> courseSystems = iCourseSystemService.selectAllCourseSystem();
        Map<String,Integer> map=new HashMap<>();
        for (int i=0;i<courseSystems.size();i++){
            map.put(courseSystems.get(i).getCourseSystemName(),courseSystems.get(i).getCourseSystemId());
        }
        for (int i=0;i<data.size();i++){
            String courseSystemName=data.get(i).get(0).toString().replaceAll(" ","");
            Integer courseSystemId=map.get(courseSystemName);
            if(courseSystemId==null){
                return Result.error(-1,"课程体系名不存在，请检查表中第"+(i+1)+"行数据。");
            }
            String courseName=data.get(i).get(1).toString().replaceAll(" ","");
            BigDecimal referenceCredit=new BigDecimal(data.get(i).get(2).toString());
            Course temp=new Course(null,courseSystemId,courseName,referenceCredit);
            boolean save = iCourseService.save(temp);
            if(!save){
                return Result.error(-1,"请检查录入数据。");
            }
        }
        return Result.success(ResultCode.SUCCESS,"插入成功");
    }

    @ApiOperation("查询所有课程总条数")
    @GetMapping("/selectAllCourseSum")
    public  Result selectAllCourseSum() {
        return Result.success(ResultCode.SUCCESS,iCourseService.selectAllCourseSum());
    }

    @ApiOperation("通过课程名称判断该课程是否存在")
    @GetMapping("/courseIsHave/{courseName}")
    public Result courseIsHave(@PathVariable("courseName") String courseName){
        Course course = iCourseService.selectCourseByCourseName(courseName);
        if(course==null) return Result.error(-1,"该课程不存在");
        return Result.success(ResultCode.SUCCESS,"该课程存在");
    }

    @ApiOperation("根据课程名模糊查询")
    @GetMapping("/selectAllCourseByCourseNameLike")
    public Result selectAllCourseByLike(String courseName){
        List<CourseVO> res=new ArrayList<>();
        List<Course> data=iCourseService.selectAllCourseByLike(courseName);
        Map<Integer, String> mapUtilsCourseSystemUtil = mapUtils.getCourseSystemUtil();
        for (int i=0;i<data.size();i++){
            Course t=data.get(i);
            res.add(new CourseVO(t.getCourseId(),t.getCourseSystemId(),mapUtilsCourseSystemUtil.get(t.getCourseSystemId()),t.getCourseName(),t.getReferenceCredit()));
        }
        return Result.success(res);
    }

}
